package com.anjie.powerproject.controller;

import com.anjie.powerproject.entity.*;
import com.anjie.powerproject.pojo.CustomEdgeMulti;
import com.anjie.powerproject.pojo.CustomRelationshipCom;
import com.anjie.powerproject.pojo.dto.DeviceInfoDTO;
import com.anjie.powerproject.pojo.dto.GraphChangeLogDTO;
import com.anjie.powerproject.pojo.dto.ModelDTO;
import com.anjie.powerproject.pojo.dto.StationInfoDTO;
import com.anjie.powerproject.service.*;

import com.anjie.powerproject.strategy.BaseWorkStrategy;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class PageController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private EnergyTypeService energyTypeService;

    @Autowired
    private RelationshipService relationshipService;

    @Autowired
    private RelationshipComService relationshipComService;

    @Autowired
    private StationInfoService stationInfoService;

    @Autowired
    private BaseWorkStrategy baseWorkStrategy;

    @Autowired
    PointService pointService;

    @Autowired
    ModelService modelService;

    @Autowired
    GraphChangeLogService graphChangeLogService;

    @GetMapping("/energyControlCenter2.html")
    public String loadEnergyControlCenter2(){
        return "energyControlCenter2";
    }

    @GetMapping("/view2.html")
    public String loadViewPage2(){
        return "view2";
    }

    @GetMapping("/view2.html/{date}")
    public String loadViewPageByTime2(@PathVariable("date") String date){
        return "view2";
    }

    @GetMapping("/strategyCenter2.html")
    public String loadStrategyCenter2(){
        return "strategyCenter2";
    }

    @GetMapping("/electricModelGenerator2.html")
    public String loadElectricModelGenerator2(){
        return "electricModelGenerator2";
    }

    @GetMapping("/energyModelGenerator2.html")
    public String loadEnergyModelGenerator2(){
        return "energyModelGenerator2";
    }

    @GetMapping("/pointConfig.html")
    public String pointConfig(){
        return "pointConfig";
    }

    @GetMapping("/knowChartChangeHistory.html")
    public String knowChartChangeHistory(Model model){
        List<GraphChangeLogDTO> graphChangeLogList = graphChangeLogService.getAll();
        model.addAttribute("graphChangeLogList",graphChangeLogList);
        return "knowChartChangeHistory";
    }

    @GetMapping("/model.html")
    public String modelPage(Model model){
        List<com.anjie.powerproject.entity.Model> modelList = modelService.getAllModel();
        List<ModelDTO> modelDTOList=new ArrayList<>();
        for (com.anjie.powerproject.entity.Model tmpModel:modelList) {
            ModelDTO modelDTO=new ModelDTO();
            BeanUtils.copyProperties(tmpModel,modelDTO);
            if(!tmpModel.getDeviceCode().equals("")||tmpModel.getDeviceCode()!=null) {
                Point point = pointService.getPointByDevCode(tmpModel.getDeviceCode());
                if(point!=null)
                    modelDTO.setPointName(point.getPointName());
                else  modelDTO.setPointName("无对应点位");
            } else modelDTO.setPointName("无对应点位");
            modelDTOList.add(modelDTO);

        }
        model.addAttribute("modelDTOList",modelDTOList);
        return "model";
    }

    @GetMapping("/pointBatchAdd.html")
    public String pointBatchAddPage(){
        return "pointBatchAdd";
    }

    @GetMapping("/pointAdd.html")
    public String pointAddPage(){
        return "pointAdd";
    }

    @GetMapping("/point.html")
    public String pointPage(Model model){
        List<Point> pointList = pointService.getPointList();
        model.addAttribute("pointList",pointList);
        return "point";
    }

    @GetMapping("/device.html")
    public String loadDevicePage1(Model model){
        List<Device> deviceList = deviceService.getAllDevices();
        List<DeviceInfoDTO> deviceInfoDTOS=new ArrayList<>();
        for (Device device:deviceList) {
            DeviceInfoDTO deviceInfoDTO=new DeviceInfoDTO();
            BeanUtils.copyProperties(device,deviceInfoDTO);
            Point devPoint=pointService.getPointByDevCode(device.getDevCode());
            deviceInfoDTO.setDevName(devPoint!=null?devPoint.getPointName():"点位不存在");
            Point BatteryPoint=pointService.getPointByDevCode(device.getBatteryCode());
            deviceInfoDTO.setBatteryName(BatteryPoint!=null?BatteryPoint.getPointName():"点位不存在");
            Point TemperaturePoint=pointService.getPointByDevCode(device.getTemperatureCode());
            deviceInfoDTO.setTemperatureName(TemperaturePoint!=null?TemperaturePoint.getPointName():"点位不存在");

            deviceInfoDTOS.add(deviceInfoDTO);
        }
        model.addAttribute("deviceInfoDTOS",deviceInfoDTOS);
        return "device";
    }

    // 设备管理-设备展示
    @GetMapping("/devices/show.html")
    public String loadDevicePage(Model model){
        List<Device> deviceList = deviceService.getAllDevices();
        List<DeviceInfoDTO> deviceInfoDTOS=new ArrayList<>();
        List<Point> pointList=pointService.getPointList();
        Map<Integer, Point> pointMap = pointList.stream().collect(Collectors.toMap(Point::getId,object -> object));

        for (Device device:deviceList) {
            DeviceInfoDTO deviceInfoDTO=new DeviceInfoDTO();
            BeanUtils.copyProperties(device,deviceInfoDTO);
            if(device.getDevPointId()!=null) {
//                Point devPoint = pointService.getPointById(device.getDevPointId());
                Point devPoint=pointMap.get(device.getDevPointId());
                deviceInfoDTO.setDevName(devPoint != null ? devPoint.getPointName() : "点位不存在");
            }
            if(device.getBatteryPointId()!=null) {
//                Point BatteryPoint = pointService.getPointById(device.getBatteryPointId());
                Point BatteryPoint = pointMap.get(device.getBatteryPointId());
                deviceInfoDTO.setBatteryName(BatteryPoint != null ? BatteryPoint.getPointName() : "点位不存在");
            }
            if(device.getTemperaturePointId()!=null) {
//                Point TemperaturePoint = pointService.getPointById(device.getTemperaturePointId());
                Point TemperaturePoint = pointMap.get(device.getTemperaturePointId());
                deviceInfoDTO.setTemperatureName(TemperaturePoint != null ? TemperaturePoint.getPointName() : "点位不存在");
            }
//            if(device.getDevPointId()!=null) {
//                Point devPoint = pointService.getPointById(device.getDevPointId());
//                deviceInfoDTO.setDevName(devPoint != null ? devPoint.getPointName() : "点位不存在");
//            }else deviceInfoDTO.setDevName("点位不存在");
//            if(device.getBatteryPointId()!=null) {
//                Point BatteryPoint = pointService.getPointById(device.getBatteryPointId() != null ? device.getBatteryPointId() : 3);
//                deviceInfoDTO.setBatteryName(BatteryPoint != null ? BatteryPoint.getPointName() : "点位不存在");
//            }else deviceInfoDTO.setBatteryName("点位不存在");
//            if(device.getTemperaturePointId()!=null) {
//                Point TemperaturePoint = pointService.getPointById(device.getTemperaturePointId() != null ? device.getTemperaturePointId() : 3);
//                deviceInfoDTO.setTemperatureName(TemperaturePoint != null ? TemperaturePoint.getPointName() : "点位不存在");
//            }else deviceInfoDTO.setTemperatureName("点位不存在");

            deviceInfoDTOS.add(deviceInfoDTO);
        }
        model.addAttribute("deviceInfoDTOS",deviceInfoDTOS);
        return "device";
    }

    // 基本信息管理
    @GetMapping("/basicInfo.html")
    public String loadInfoPage(Model model) {
        List<StationInfo> stationInfoList = stationInfoService.findAllInfo();
        StationInfo stationInfo=stationInfoList.get(0);

        StationInfoDTO stationInfoDTO=new StationInfoDTO();
        BeanUtils.copyProperties(stationInfo,stationInfoDTO);

        if(stationInfo.getBatteryPointId()!=null) {
            String batteryName = pointService.getPointById(stationInfo.getBatteryPointId()).getPointName();
            stationInfoDTO.setBatteryName(batteryName);
        } else stationInfoDTO.setBatteryName("无对应点位");
        if(stationInfo.getEnergyPointId()!=null) {
            String energyName = pointService.getPointById(stationInfo.getEnergyPointId()).getPointName();
            stationInfoDTO.setEnergyName(energyName);
        }else stationInfoDTO.setEnergyName("无对应点位");
//        String temperatureName=pointService.getPointById(stationInfo.getTemperaturePointId()).getPointName();
//        stationInfoDTO.setTemperatureName(temperatureName);
//        System.out.println(stationInfoDTO.toString());
        List<StationInfoDTO> stationInfoDTOList=new ArrayList<>();
        stationInfoDTOList.add(stationInfoDTO);
        model.addAttribute("stationInfoDTOList",stationInfoDTOList);
        return "basicInfo";
    }

    @GetMapping("/main.html")
    public String show_station_name(Model model) {
        List<StationInfo> stationInfoList = stationInfoService.findAllInfo();
        model.addAttribute("stationInfoList",stationInfoList);
        StationInfo stationInfo = stationInfoList.get(0);
        String stationName = stationInfo.getStationName();
        System.out.println(stationName);
        model.addAttribute("stationInfoList_show_name",stationName);
        return "main";
    }

    // 图谱管理
    @GetMapping("/graph.html")
    public String loadGraphPage(Model model) throws ParseException {
        List<GraphInfo> allGraphInfo = graphInfoService.getAllGraphInfo();
        //List<GraphInfo> allGraphInfo = graphInfoService.findGraphInfosByRemark(remark);
        model.addAttribute("graphInfoList",allGraphInfo);
        // 这里增加一个判断图谱使用时间是否闭合的判断，并将状态发回前端
        // 判断方法：如果时间段是闭合的，那么也就是说，当前遍历的时间段的起始时间的前一天和结束时间的后一天一定在其他图谱中出现过(这里是不需要考虑跨年问题的)
        List<String> startTimes = allGraphInfo.stream().map(item->item.getGraphStartTime()).collect(Collectors.toList());
        List<String> endTimes = allGraphInfo.stream().map(item->item.getGraphEndTime()).collect(Collectors.toList());
        for (GraphInfo graphInfo : allGraphInfo) {
            String time1 = DateUtils.mdFormat.format(DateUtils.plusOrMinusDay(DateUtils.mdFormat.parse(graphInfo.getGraphEndTime()), 1).getTime());
            String time2 = DateUtils.mdFormat.format(DateUtils.plusOrMinusDay(DateUtils.mdFormat.parse(graphInfo.getGraphStartTime()), -1).getTime());
            // time1 应该在 startTimes中存在，time2 应该在endTimes中存在
            if (!startTimes.contains(time1) || !endTimes.contains(time2)) {
                model.addAttribute("flag", false);
                break;
            }
        }
        if (!model.containsAttribute("flag")) {
            model.addAttribute("flag", true);
        }
        return "knowChart";
    }

    // 电价
    @GetMapping("/electricity.html")
    public String loadElePage(Model model) {
        return "elePrice";
    }

    // 能源属性
    @GetMapping("/energy.html")
    public String loadEnergyPage(Model model) {
        List<EnergyType> allEnergyType = energyTypeService.getAllEnergyType();
        model.addAttribute("energyTypeList",allEnergyType);
        return "property";
    }

    // 策略库管理
    @GetMapping("/relationship.html")
    public String loadRelationshipPage(Model model) {
        List relationshipList = relationshipService.findCustomRelationshipList();
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("relationshipList",relationshipList);
        model.addAttribute("graphInfoList",graphInfoList);
        return "edge";
    }
    //  组合策略管理
    @GetMapping("/relationshipCom.html")
    public String loadEdgeMultiPage(Model model){
        List<Integer> stgyCodes = relationshipComService.findAllStgyCode();
        List<CustomEdgeMulti> customEdgeMultiList = new ArrayList<CustomEdgeMulti>();
        for(Integer stgyCode : stgyCodes){
            List<CustomRelationshipCom> list = new ArrayList<>();
            list = relationshipComService.findCustomRelationshipComListByStgyCode(stgyCode);
            List<CustomEdgeMulti> customEdgeMulti = relationshipComService.findCustomEdgeMulti(list);
            customEdgeMultiList.add(customEdgeMulti.get(0));
        }
        List graphInfoList = graphInfoService.getAllGraphInfo();
        model.addAttribute("relationshipComList",customEdgeMultiList);
        model.addAttribute("graphInfoList",graphInfoList);
        return "edgeMulti";
    }

    // 图谱位置调整
    @GetMapping("/drag.html")
    public String loadDragPage(Model model) throws ParseException {
        List<GraphInfo> graphInfoList = graphInfoService.getAllGraphInfo();
        Integer graphId = baseWorkStrategy.getGraphId();
        GraphInfo graphInfo = graphInfoService.findGraphInfoById(graphId);
        model.addAttribute("graphId",graphId);
        model.addAttribute("currentGraph",graphInfo);
        model.addAttribute("graphList",graphInfoList);
        return "dragChart";
    }

    @GetMapping("/view.html")
    public String loadViewPage(){
        return "view";
    }

    @GetMapping("/view.html/{date}")
    public String loadViewPageByTime(@PathVariable("date") String date){
        return "view";
    }

    @GetMapping("/jilin.html")
//    @GetMapping("/modeView.html")
    public String getInfosToMultiModeByNow(){
        return "multiModeView";
    }

    @GetMapping("/jilin.html/{date}")
//    @GetMapping("/modeView.html/{date}")
    public String getInfosToMultiModeViewByDate(@PathVariable("date") String date){
        return "multiModeView";
    }
    
    @GetMapping("/viewChart.html")
    public String loadViewChartPage(){
        return "viewChart";
    }

    @GetMapping("/viewChart.html/{date}")
    public String loadViewChartPageByTime(@PathVariable("date") String date){
        return "viewChart";
    }

    @GetMapping("/energyControlCenter.html")
    public String loadEnergyControlCenter(){
        return "energyControlCenter";
    }

    @GetMapping("/strategyCenter.html")
    public String loadStrategyCenter(){
        return "strategyCenter";
    }

    @GetMapping("/electricModelGenerator.html")
    public String loadElectricModelGenerator(){
        return "electricModelGenerator";
    }    
    @GetMapping("/energyModelGenerator.html")
    public String loadEnergyModelGenerator(){
        return "energyModelGenerator";
    }    

    @GetMapping("gongkuangModify.html")
    public String loadModelGongkuangModify(){
        return "gongkuangModify";
    }

    @GetMapping("gongkuangUpgrade.html")
    public String loadGongkuangUpgrade(){
        return "gongkuangUpgrade";
    }
}
